package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"sync"
)

var Logs *log.Logger

type SSHProxy struct {
	mu           sync.RWMutex
	registryPath string             `json:"-"`
	AppInfos     map[string]AppInfo `json:"data"` //registry里面的AppInfo
	Port         string             `json:"port"`
}

func (dp *SSHProxy) RegClientKey(appid, client, pk string) { //pass
	dp.mu.Lock() //读写锁
	defer dp.mu.Unlock()
	dp.AppInfos[appid].TrustedClientKeys[client] = pk //TrustedClientKeys在json中未定义
	dp.save()
}

func (dp *SSHProxy) Load() error {
	dp.mu.Lock()
	defer dp.mu.Unlock()
	f := dp.registryPath               //文件路径、文件名，registryPath在json中未定义
	content, err := ioutil.ReadFile(f) // ReadFile(f):读取文件名，返回文件内容
	if err != nil {
		return err
	}
	err = json.Unmarshal(content, dp) //将content编译为dp的形式
	if err != nil {
		return err
	}
	dp.registryPath = f
	if dp.Port == "" {
		return fmt.Errorf("missing port")
	}
	return nil
}

func NewSSHProxy(f string) (*SSHProxy, error) {
	proxy := &SSHProxy{}
	proxy.registryPath = f //json文件路径
	err := proxy.Load()
	return proxy, err
}

func (dp *SSHProxy) save() error {
	content, err := json.Marshal(dp) //把dp编译为json格式（{“”：“”}）
	if err != nil {
		return err
	}
	if err := ioutil.WriteFile(dp.registryPath+".tmp", content, os.FileMode(0644)); err != nil {
		return err //此方法是将content写入.tmp文件中
	}
	if err := os.Rename(dp.registryPath+".tmp", dp.registryPath); err != nil {
		return err //将.tmp文件重命名/替代为dp.registryPath文件
	}
	return nil
}

func main() {
	logfile, err := os.Create("proxy.log") //新建log文件
	if err != nil {
		fmt.Print(err)
	}
	logger := log.New(logfile, "", log.Ldate|log.Ltime)
	Logs = logger
	defer logfile.Close()
	p, err := NewSSHProxy("testdata/reg.json")
	if err == nil {
		//定时save 或者load一次？
		fmt.Println(p.serve())
	}
}

/*
Step 1. Create key (password protected)
openssl genrsa -out prvtkey.pem 1024/2038                     (with out password protected)
openssl genrsa -out dummy-genrsa.pem 2048
*/
